package com.dacool.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.dacool.app.sale.R;
import com.dacool.util.ViewUtils;

public class BorderedImageView extends ImageView {

	private boolean isOval;
	private int borderColor;
	private int borderWidth;

	public BorderedImageView(Context context) {
		this(context, null);
	}

	public BorderedImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		TypedArray attrArray = context.obtainStyledAttributes(attrs,
				R.styleable.BorderedImageView);
		borderColor = attrArray.getColor(
				R.styleable.BorderedImageView_border_color, Color.TRANSPARENT);
		borderWidth = attrArray.getDimensionPixelSize(
				R.styleable.BorderedImageView_border_width, 0);
		isOval = attrArray.getBoolean(R.styleable.BorderedImageView_is_oval,
				false);
		attrArray.recycle();
	}

	public void setDrawableID(int resID) {
		this.setDrawable(getResources().getDrawable(resID));
		;

	}

	public void setDrawable(Drawable drawable) {
		if (isOval && drawable instanceof BitmapDrawable) {
			Bitmap bm = ViewUtils
					.circleBitmapWithoutRing(((BitmapDrawable) drawable)
							.getBitmap());
			this.setImageBitmap(bm);
		} else
			super.setImageDrawable(drawable);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		Paint paint = new Paint();
		paint.setColor(borderColor);
		paint.setStrokeWidth(borderWidth);
		if (!isOval) {
			canvas.drawLine(0, 0, getWidth(), 0, paint);
			canvas.drawLine(getWidth(), 0, getWidth(), getHeight(), paint);
			canvas.drawLine(getWidth(), getHeight(), 0, getHeight(), paint);
			canvas.drawLine(0, getHeight(), 0, 0, paint);
		}
	}
}
